#!/usr/bin/env python3
import sys
import os
import struct

#if len(sys.argv) < 2:
#    sys.stderr.write("usage: "+sys.argv[0]+" <input> <output>\n")
#    sys.exit(1)
#
#file = open(sys.argv[1], 'rb')
#
#datain = file.read();
#
#for i in range(4):
#    print("input data = ", datain[i])
#
#dataout = struct.unpack('<I',datain)[0]
#
#file = open('sys.argv[2]', 'wb')
#
#file.write(dataout)
#
#file.close()

#big/little-endian 32bits convert
# main body
if sys.argv.__len__() > 1:
# get parameters
    src_file = sys.argv[1]
else:
# text input
    src_file = input("Source Bin Path: ")

dst_file = src_file[0:(src_file.__len__()-4)]
dst_i_file = dst_file
dst_file += "_le.bin"
dst_i_file += ".i"

print("Source file: {0}\nTarget File: {1}\n\t: {2}".format(src_file, dst_file, dst_i_file))

sf = open(src_file, "rb")
df = open(dst_file, "wb")
dif = open(dst_i_file, "w")

buf_tmp = [b'0'for x in range(0, 4)]

contents = sf.read()
buf_size = contents.__len__()
extra_size = (buf_size % 4)
print("Src    size: %d KHz " % (buf_size/1024))
#print("extra_size=",extra_size)

if extra_size > 0:
    buf_size += (4 - extra_size)
contents = contents + b'0000'
for i in range(0, buf_size, 4):
    buf_tmp[3] = contents[i]
    buf_tmp[2] = contents[i+1]
    buf_tmp[1] = contents[i+2]
    buf_tmp[0] = contents[i+3]
    #print("i= buf_tmp= ", i, buf_tmp[3],  buf_tmp[2],  buf_tmp[1],  buf_tmp[0])
    if (i > 0) and ((i % 16) == 0):
        dif.write("\n")
    for j in range(0, 4):
        dif.write(str.format("0x%02x," % buf_tmp[j]))
    # pack into bytes flow
    tmp_bytes = struct.pack("4B", buf_tmp[0], buf_tmp[1], buf_tmp[2], buf_tmp[3])
    #print("tmp_bytes=", tmp_bytes)
    df.write(tmp_bytes)

dif.close()
sf.close()
df.close()
print("Convert Completed!")
